# coding: utf8
from __init__ import *

import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
get_wsgi_application()

import tornado.web
import tornado.ioloop
from urllib.parse import urlencode
from tornado.testing import AsyncHTTPTestCase
from settings import TORNADO_ENV
from urls import urls
import json
from backend.models import *
from functools import partialmethod
from hashlib import md5


class ControllerTestCase(AsyncHTTPTestCase):
    # 增加登陆token
    s = '%s|%s|huanxicm' % (1, 'admin')
    admin_token = md5(s.encode('utf8')).hexdigest() + '|%s' % 1

    def setUp(self):
        super().setUp()
        self.remove_data()
        self.prepare_data()

    def tearDown(self):
        super().tearDown()
        self.remove_data()

    def prepare_data(self):
        pass
        

    def remove_data(self):
        pass

    def get_new_ioloop(self):
        return tornado.ioloop.IOLoop.instance()

    def get_app(self):
        return tornado.web.Application(urls, **TORNADO_ENV)

    def get(self, url, data=None, headers=None):
        if data is not None:
            if isinstance(data, dict):
                data = urlencode(data)
            if '?' in url:
                url += '&amp;%s' % data
            else:
                url += '?%s' % data
        return self._fetch(url, 'GET', headers=headers)

    def post(self, url, data, headers=None):
        if data is not None:
            if isinstance(data, dict):
                data = json.dumps(data)

        return self._fetch(url, 'POST', data, headers)

    def _fetch(self, url, method, data=None, headers=None):
        self.http_client.fetch(
            self.get_url(url), self.stop, method=method, body=data, headers=headers
        )
        return self.wait()

    admin_post = partialmethod(post, headers={'Authorization': admin_token})

    admin_get = partialmethod(get, headers={'Authorization': admin_token})
